package ren.nearby.http.utils.util;

import android.annotation.TargetApi;
import android.os.Build;
import android.util.ArrayMap;

import com.orhanobut.logger.Logger;


import java.util.Set;


import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2018/5/22 0022.
 */

public class RxDisposble implements RxDisposbleAction<Object> {
    private static RxDisposble instance = null;
    private ArrayMap<Object, Disposable> maps;

    private RxDisposble() {
        maps = new ArrayMap<>();
    }

    public static RxDisposble getInstance() {
        if (instance == null) {
            synchronized (RxDisposble.class) {
                if (instance == null) {
                    instance = new RxDisposble();
                }

            }

        }
        return instance;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void add(Object tag, Disposable disposable) {
        maps.put(tag, disposable);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void remove(Object tag) {
        if (!maps.isEmpty()) {
            maps.remove(tag);
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void removeAll() {
        if (!maps.isEmpty()) {
            maps.clear();
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void cancel(Object tag) {
        if (maps.isEmpty()) {
            return;
        }
        if (maps.get(tag) == null) {
            return;
        }
        if (!maps.get(tag).isDisposed()) {
            maps.get(tag).dispose();
            maps.remove(tag);
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void cancelAll() {
        if (maps.isEmpty()) {
            return;
        }
        Set<Object> keys = maps.keySet();
        for (Object apiKey : keys) {
            cancel(apiKey);
        }
    }


    public CompositeDisposable mCompositeSubscription;

    public void unSubscribe() {
        if (mCompositeSubscription != null) {
            Logger.e("unsubscribe start ");
            mCompositeSubscription.dispose();
        }
        Logger.e("unsubscribe end ");
    }

    public void addSubscrebe(Disposable subscription) {
        if (mCompositeSubscription == null) {
            Logger.e("addSubscrebe  start ");
            mCompositeSubscription = new CompositeDisposable();

        }
        mCompositeSubscription.add(subscription);
        Logger.e("addSubscrebe end ");
    }


}
